<template>
  <el-dialog
    title="编辑json"
    width="40%"
    :append-to-body="true"
    :visible.sync="showTag"
  >
    <el-row v-for="(data, idx) in form" :key="idx" :class="{ mt10: idx > 0 }">
      <el-col :span="11" class="pr5">
        <el-input v-model="data.key" size="mini" placeholder="key"></el-input>
      </el-col>
      <el-col :span="11" class="pl5">
        <el-input
          v-model="data.value"
          size="mini"
          placeholder="value"
        ></el-input>
      </el-col>
      <el-col v-if="idx > 0" :span="2" class="pl5">
        <span class="color_main fs14 pointer" @click="del(idx)">删除</span>
      </el-col>
    </el-row>
    <div slot="footer">
      <el-button size="mini" @click="hide">取消</el-button>
      <el-button type="success" size="mini" @click="add">添加</el-button>
      <el-button type="primary" size="mini" @click="sub">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getJsDataType, isEmpty } from "../lib/utils";

export default {
  name: "SimpleJsonDialog",
  data() {
    return {
      form: [],
      showTag: false
    };
  },
  methods: {
    show(info) {
      if (isEmpty(info)) {
        this.form.push({ key: "", value: "" });
      } else {
        if (getJsDataType(info) === "[object String]") info = JSON.parse(info);
        // eslint-disable-next-line no-unused-vars
        for (const key in info) {
          this.form.push({
            key,
            value: info[key]
          });
        }
      }
      this.showTag = true;
    },
    hide() {
      this.form.splice(0);
      this.showTag = false;
    },
    add() {
      this.form.push({ key: "", value: "" });
    },
    del(idx) {
      this.form.splice(idx, 1);
    },
    sub() {
      const res = {};
      this.form.forEach(({ key, value }) => {
        res[key] = value;
      });
      this.$emit("ok", res);
      this.hide();
    }
  }
};
</script>

<style scoped></style>
